<template>
  <div class="address-edit-page">
    <ul class="form">
      <li>
        <span class="text">收件人姓名:</span>
        <span class="input">
          <cube-input v-model="postForm.nickname" placeholder="请输入收件人姓名" clearable />
        </span>
      </li>
      <li>
        <span class="text">收件人电话:</span>
        <span class="input">
          <cube-input v-model="postForm.mobile" placeholder="请输入收件电话号码" clearable />
        </span>
      </li>
      <li>
        <span class="text">请选择地区:</span>
        <!-- 这里如果是编辑时,一定要判断city.addressIndex.length,否则子组件获取不到数据 -->
        <city-selector
          v-if="showCity"
          class="city"
          :class="{'active': city.cityActive}"
          :edit-selected="city.addressIndex"
          @citySelected="citySelected">
          <span style="color: #333">{{city.text}}</span>
        </city-selector>
      </li>
      <li>
        <span class="text">详细地址:</span>
        <span class="input info">
          <cube-textarea v-model="postForm.info" placeholder="请输入详细地址" :autofocus="$route.params.id > 0" />
        </span>
      </li>
      <li class="last">
        <span class="text">是否设为默认地址</span>
        <span class="input">
          <cube-switch v-model="postForm.isDefault" />
        </span>
      </li>
    </ul>
    <footer-button
      icon="cubeic-right"
      :text="buttonText"
      @submit="saveAddress"
    />
    <loading :show="loading" />
  </div>
</template>

<script>
import FooterButton from './components/FooterButton'
import CitySelector from './components/CitySelector'
import api from '@/api'
import Loading from '@/components/Loading'
export default {
  name: 'AddressEdit',
  components: {
    FooterButton,
    CitySelector,
    Loading
  },
  computed: {
    buttonText() {
      return this.$route.params.id && this.$route.params.id > 0 ? '更新' : '保存'
    },
    // edit => selected
    showCity() {
      if (this.$route.params.id > 0) {
        return this.city.addressIndex.length > 0
      } else {
        return true
      }
    }
  },
  watch: {
    showHeight() {
      if (this.docHeight > this.showHeight) {
        this.hideShow = false
      } else {
        this.hideShow = true
      }
    }
  },
  data() {
    return {
      postForm: {},
      city: {
        // selected
        addressIndex: [],
        text: '',
        cityActive: false,
        // selected id => db
        cityMap: []
      },
      loading: false,
      hideShow: false,
      // footer
      docHeight: document.documentElement.clientHeight || document.body.clientHeight,
      showHeight: document.documentElement.clientHeight || document.body.clientHeight
    }
  },
  methods: {
    // CitySelector result
    citySelected(args) {
      const { selectedVal, selectedText } = args
      this.city.text = selectedText.join(', ')
      this.city.cityActive = true
      this.city.cityMap = selectedVal
    },
    // save
    saveAddress() {
      if (!this.postForm.nickname || !this.postForm.mobile || !this.postForm.info || this.city.cityMap.length === 0) {
        this.$createToast({
          type: 'error',
          txt: '请填写完整'
        }).show()
      } else if (!/^1[3456789]\d{9}$/.test(this.postForm.mobile)) {
        this.$createToast({
          type: 'error',
          txt: '手机号码错误'
        }).show()
      } else {
        const [provinceId, cityId, areaId] = this.city.cityMap
        this.loading = true
        api.Address.edit({
          id: this.$route.params.id,
          province_id: provinceId,
          city_id: cityId,
          area_id: areaId,
          // ...this.postForm,
          is_default: this.postForm.isDefault ? 1 : 0,
          mobile: this.postForm.mobile,
          nickname: this.postForm.nickname,
          address: this.postForm.info
        }).then(() => {
          this.$createToast({
            type: 'txt',
            txt: '操作成功',
            time: 500,
            onTimeout: () => {
              // order address
              // see views/order/components/Address.vue
              if (+this.$route.params.id === -2) {
                this.$router.back()
              } else {
                this.$router.push('/service/address-list')
              }
            }
          }).show()
        }).finally(() => {
          this.loading = false
        })
      }
    }
  },
  created () {
    // default user info
    const info = this.$store.getters['ExecUser/info']
    if (Object.keys(info).length > 0) {
      this.postForm = Object.assign({}, { ...info, isDefault: true })
    }
    // edit default data
    if (this.$route.params.id && this.$route.params.id > 0) {
      this.loading = true
      api.Address.view({ id: this.$route.params.id }).then(response => {
        const { data } = response
        this.postForm = Object.assign({}, {
          ...data,
          isDefault: data.is_default === '1',
          info: data.address
        })
        const { city } = data
        const selected = [city.province_id, city.city_id, city.area_id]
        this.city = {
          addressIndex: selected,
          text: `${city.province},${city.city},${city.area}`,
          cityMap: selected,
          cityActive: true
        }
      }).finally(() => {
        this.loading = false
      })
    }
  },
  mounted () {
    // key => fixed bug
    window.onresize = () => {
      return (() => {
        this.showHeight = document.documentElement.clientHeight || document.body.clientHeight
      })()
    }
  }
}
</script>

<style scoped lang="stylus">
.address-edit-page
  .form
    padding 10px
    li
      padding 10px
      span
        display block
        height 40px
        &.info
          height 50px
        &.text
          height 20px
          text-align left
          font-weight 700
          font-size 14px
      &.last
        // 解决遮住
        margin-top 20px

  // 地址选择器
  .city
    //background white
    //width 100%
    height 40px
    line-height 40px
    text-align left
    //padding-left 10px
    //border 0.5px solid #ebebeb
    color #d0d0d0
    box-sizing border-box
    &.active
      color red
</style>
